package com.ricervcvcer.user.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ricervcvcer.common.util.ResultEntity;
import com.ricervcvcer.user.entity.SysGroup;
import com.ricervcvcer.user.service.ISysGroupService;
import com.ricervcvcer.user.util.RicervcvcerConstant;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author moge
 * @since 2022-01-10
 */
@RestController
@RequestMapping("sys-group")
public class SysGroupController {

    @Autowired
    ISysGroupService groupService;

    @ApiOperation("查询所有用户组")
    @GetMapping("getGroups")
    public ResultEntity<List<SysGroup>> getGroups() {
        List<SysGroup> list = groupService.list();
        return ResultEntity.successWithData(list);
    }

    @ApiOperation("分页查询分组")
    @PostMapping("page")
    public ResultEntity page(
            @ApiParam("页码") @RequestParam Integer page,
            @ApiParam("每页条数") @RequestParam Integer rows,
            @ApiParam("用户名") @RequestParam String groupName){
        Page<SysGroup> list = groupService.page(page,rows,groupName);
        return ResultEntity.successWithData(list);
    }

    @ApiOperation("根据id修改分组访问信息")
    @PostMapping("update")
    public ResultEntity update(
            @ApiParam("分组信息") @RequestBody SysGroup group){
        boolean b = groupService.updateById(group);
        if(!b)
            throw new RuntimeException(RicervcvcerConstant.UPDATE_ERROR);
        return ResultEntity.successWithoutData();
    }

    @ApiOperation("根据id查询分组数据")
    @GetMapping("selectById/{id}")
    public ResultEntity selectById(@ApiParam("分组id") @PathVariable Integer id){
        return ResultEntity.successWithData(groupService.getById(id));
    }

    @ApiOperation("添加一个分组")
    @PostMapping("add")
    public ResultEntity add(
            @ApiParam("分组信息") @RequestBody SysGroup group){

        // 查询要添加的用户是否已经存在
        QueryWrapper qw = new QueryWrapper<>();
        qw.eq("grp_name",group.getGrpName());
        SysGroup one = groupService.getOne(qw);
        if(!StringUtils.isEmpty(one)){
            throw new RuntimeException("已经存在该组名！");
        }
        boolean b = groupService.save(group);
        if(!b)
            throw new RuntimeException(RicervcvcerConstant.ADD_ERROR);
        return ResultEntity.successWithoutData();
    }


    @DeleteMapping("delete/{id}")
    @ApiOperation("删除一个分组")
    public ResultEntity delete(@ApiParam("grpId") @PathVariable Integer id){
        boolean b = groupService.removeById(id);
        if(!b){
            throw new RuntimeException("删除成功！");
        }
        return ResultEntity.successWithoutData();
    }
}
